#pragma strict
/////////////////////////////////////////////////////////////////////
// 第三人称摄影机
/////////////////////////////////////////////////////////////////////
class TPSCamera extends BaseCamera{
	var x:float; //x,y,旋转值累计.
	var y:float;

	var speed:Vector2 = Vector2(1,1); //绕y,x旋转的速度.
	var xRange:Vector2 = Vector2(-80,80); //x轴的旋转范围.
	
	var dist:float = 10; //到目标的距离
	var raycastDist:float; //到碰撞点的距离
	var finalDist:float;
	var distanceRange:Vector2 = Vector2(5,24); //到目标点最小最大距离.
	
	var smoothSpeed:float = 0.8;

	function Start () {
		super.Start();
		offsetDir = Vector3.zero;
		//保存开始时的旋转
		x += tr.localEulerAngles.y;
		y += tr.localEulerAngles.x;
	}

	function Update () {
		//旋转摄影机.
		var q:Quaternion = GetRotation();
		tr.rotation = q;
		
		if(target){
			//移动到 目标的后面. 
			ClampDistance();
			
			offsetDir = q * (Vector3(0,0,-dist + raycastDist));//需要向后方向,所以为负
			var targetPos:Vector3 = target.position + offsetDir;
			
			// tr.position = targetPos;
			tr.position = Vector3.Lerp(tr.position,targetPos,smoothSpeed);
		}
		
	}
	function GetRotation():Quaternion{
		var mouseX:float = Input.GetAxis("Mouse X");
		var mouseY:float = Input.GetAxis("Mouse Y");
		
		var deltaX:float = mouseX * speed.x;
		var deltaY:float = mouseY * speed.y;
		x += deltaX;
		y -= deltaY;;
		
		y = Mathf.Clamp(y,xRange.x,xRange.y);
		
		var q:Quaternion = Quaternion.Euler(y,x,0);
		return q;
	}
	
	function ClampDistance(){
		if(dist < distanceRange.x)
			dist = distanceRange.x;
		else if(dist > distanceRange.y)
			dist = distanceRange.y;
		return dist;
	}
}
